package com.naizhuai.ui.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.naizhuai.R;
import com.naizhuai.util.DeviceUtils;


/**
 * 多行下划线的editCText
 * Created by code_han on 2018/6/13.
 */

public class EditTextMultiLine extends AppCompatTextView {
    /*
    * 文本框的背景颜色
    */
    private int backColor;
    /*
     * 画线的画笔
     */
    private Paint linePaint;
    /*
     * 画笔画线的颜色
     */
    private int paintColor;
    /*
     * 每一行的高度
     */
    private int lineHeight;
    /*
     * 行数
     */
    private int count;

    private int lineBottomHeight;

    private float lineSapce;

    /**
     * 自定义的UI类应该拥有这个构造器，否则将不能xml文件将不能加载这个UI类
     *
     * @param context 必须
     * @param attrs   必须拥有
     */
    public EditTextMultiLine(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EditTextMultiLine);
        lineBottomHeight = typedArray.getDimensionPixelSize(R.styleable.EditTextMultiLine_line_bottom_height, 0);
        backColor = Color.WHITE;
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeWidth(1);
        paintColor = R.color.text_divide_line;
        typedArray.recycle();
    }

    /**
     * 在这个方法里面画出下划线出来
     *
     * @param canvas 画布
     */
    public void onDraw(Canvas canvas) {
        //画背景颜色
        canvas.drawColor(Color.WHITE);
        //获取行的高度
        lineHeight = getLineHeight();
        //获取到底部的距离
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            lineSapce = getLineSpacingExtra() - lineBottomHeight;
        }
        count = getHeight() / lineHeight;
        //记录画到哪一行
        int nextLine = 0;
        //因为这个组件可能给它设置了边距，所以要先画第一条线
        nextLine = getCompoundPaddingTop();
        //给画笔设置颜色
        linePaint.setColor(ContextCompat.getColor(getContext(), paintColor));
        //画线
        for (int i = 0; i < getLineCount(); i++) {
            nextLine += lineHeight;
            int drawLine = (int) (nextLine - lineSapce);
            canvas.drawLine(getLeft(), drawLine, getRight(), drawLine, linePaint);
            canvas.save();
        }
        //画出光标，让他能够编辑
        super.onDraw(canvas);
    }
}
